<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-row v-show="showSearch">
				<el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
					<el-form-item label="项目编号" prop="projectNumber">
						<el-input placeholder="请输入项目编号" v-model="state.queryForm.projectNumber" />
					</el-form-item>
					<el-form-item label="项目名称" prop="projectName">
						<el-input placeholder="请输入项目名称" v-model="state.queryForm.projectName" />
					</el-form-item>
					<el-form-item label="项目类型" prop="projectType">
						<el-select v-model="state.queryForm.projectType" placeholder="请选择项目类型">
							<el-option :label="item.label" :value="item.value" v-for="(item, index) in project_type" :key="index"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="项目当前状态" prop="projectStatus">
						<el-select v-model="state.queryForm.projectStatus" placeholder="请选择项目状态">
							<el-option :label="item.label" :value="item.value" v-for="(item, index) in project_status" :key="index"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button icon="search" type="primary" @click="getDataList"> 查询 </el-button>
						<el-button icon="Refresh" @click="resetQuery">重置</el-button>
						<el-button @click="downloadFiles">导出项目和文件</el-button>
					</el-form-item>
				</el-form>
			</el-row>

			<el-row>
				<div class="mb8" style="width: 100%">
					<right-toolbar
						v-model:showSearch="showSearch"
						:export="'oa_projectBasicInfo_export'"
						@exportExcel="exportExcel"
						class="ml10 mr20"
						style="float: right"
						@queryTable="getDataList"
					></right-toolbar>
				</div>
			</el-row>
			<el-table
				:data="state.dataList"
				v-loading="state.loading"
				border
				:cell-style="tableStyle.cellStyle"
				:header-cell-style="tableStyle.headerCellStyle"
				@sort-change="sortChangeHandle"
			>
				<el-table-column fixed prop="projectName" label="项目名称" width="110" show-overflow-tooltip />
				<el-table-column prop="projectType" label="项目类型" width="100" show-overflow-tooltip>
					<template #default="scope">
						<dict-tag :options="project_type" :value="scope.row.projectType"></dict-tag>
					</template>
				</el-table-column>
				<el-table-column fixed prop="projectStatus" label="项目当前状态" width="120" show-overflow-tooltip>
					<template #default="scope">
						<dict-tag :options="project_status" :value="scope.row.projectStatus"></dict-tag>
					</template>
				</el-table-column>
				<el-table-column fixed prop="projectStatus" label="是否立项" width="100" show-overflow-tooltip>
					<template #default="scope">
						<dict-tag :options="project_approval_status" :value="scope.row.projectApprovalStatus"></dict-tag>
					</template>
				</el-table-column>

				<el-table-column fixed prop="projectNumber" label="项目编号" width="130" show-overflow-tooltip />
				<el-table-column fixed prop="projectAbbr" label="项目缩写" width="100" show-overflow-tooltip />
				<!--				<el-table-column prop="projectYear" label="项目年份" width="100" show-overflow-tooltip />-->
				<el-table-column prop="province" label="省份" width="120" show-overflow-tooltip />
				<el-table-column prop="area" label="地区" width="120" show-overflow-tooltip />
				<el-table-column prop="projectApprovalDate" width="130" label="项目立项日期" show-overflow-tooltip />
				<el-table-column prop="projectSchedule" label="项目进度" width="110" show-overflow-tooltip />
				<el-table-column prop="bidServiceFeeInvoice" label="附件" show-overflow-tooltip>
					<template #default="scope">
						<div v-for="item in scope.row.fileList" :key="item.id">
							<a class="cursor-pointer" @click.prevent="downloadFile(item)">{{ item.original }}</a>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="remark" label="备注" show-overflow-tooltip />
				<el-table-column fixed="right" label="操作" width="150">
					<template #default="scope">
						<span v-if="scope.row.projectStatus != 'complete' && scope.row.projectStatus != 'close'">
							<el-button
								icon="VideoPlay"
								text
								type="primary"
								v-if="scope.row.projectStatus == 'ready'"
								v-auth="'oa_projectBasicInfo_edit'"
								@click="handleProjectStatus(scope.row.id, 'start')"
							></el-button>
							<el-button
								icon="CircleClose"
								text
								type="danger"
								v-else
								v-auth="'oa_projectBasicInfo_edit'"
								@click="handleProjectStatus(scope.row.id, 'close')"
							></el-button>
							<el-button
								icon="Lock"
								text
								type="danger"
								v-if="scope.row.projectStatus == 'doing'"
								v-auth="'oa_projectBasicInfo_edit'"
								@click="handleProjectStatus(scope.row.id, 'waiting')"
							></el-button>
							<el-button
								icon="Unlock"
								text
								type="warning"
								v-if="scope.row.projectStatus == 'waiting'"
								v-auth="'oa_projectBasicInfo_edit'"
								@click="handleProjectStatus(scope.row.id, 'doing')"
							></el-button>

							<el-button
								icon="edit-pen"
								text
								type="primary"
								v-auth="'oa_projectBasicInfo_edit'"
								@click="formDialogRef.openDialog(scope.row.id)"
							></el-button>
							<!--交付按钮-->
							<el-button
								icon="Finished"
								text
								type="primary"
								v-auth="'oa_projectBasicInfo_edit'"
								v-if="scope.row.projectStatus != 'ready'"
								@click="handleProjectStatus(scope.row.id, 'complete')"
							></el-button>
						</span>
					</template>
				</el-table-column>
			</el-table>
			<pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
		</div>

		<!-- 编辑、新增  -->
		<form-dialog ref="formDialogRef" @refresh="getDataList(false)" />
	</div>
</template>

<script setup lang="ts" name="systemProjectBasicInfo">
import { BasicTableProps, useTable } from '@/hooks/table';
import { fetchList, updateProjectStatusById } from '@/api/oa/projectBasicInfo';
import { useMessage, useMessageBox } from '@/hooks/message';
import { useDict } from '@/hooks/dict';
import other from '@/utils/other';
import axios from 'axios';
import { Session } from '@/utils/storage';

const { project_type, project_status, project_approval_status } = useDict('project_type', 'project_status', 'project_approval_status');

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
// 定义查询字典

// 定义变量内容
const formDialogRef = ref();
// 搜索变量
const queryRef = ref();
const showSearch = ref(true);
// 多选变量
const selectObjs = ref([]) as any;

const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {},
	pageList: fetchList,
});

//  table hook
const { getDataList, currentChangeHandle, sizeChangeHandle, sortChangeHandle, downBlobFile, tableStyle } = useTable(state);

// 清空搜索条件
// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
const resetQuery = () => {
	// 清空搜索条件
	queryRef.value?.resetFields();
	// 清空多选
	selectObjs.value = [];
	getDataList();
};

// 导出excel
const exportExcel = () => {
	downBlobFile('/oa/projectBasicInfo/export', Object.assign(state.queryForm, { ids: selectObjs }), '项目信息表.xlsx');
};

const handleProjectStatus = async (id: string, status: string) => {
	try {
		let msg = '';
		switch (status) {
			case 'start':
				msg = '是否启动此项目？';
				break;
			case 'doing':
				msg = '是否取消此项目挂起？';
				break;
			case 'waiting':
				msg = '是否挂起此项目？';
				break;
			case 'complete':
				msg = '是否完成此项目？此操作不可撤销!';
				break;
			case 'close':
				msg = '是否关闭此项目？此操作不可撤销!';
				break;
		}
		await useMessageBox().confirm(msg);
	} catch {
		return;
	}

	try {
		await updateProjectStatusById(id, status);
		getDataList();
		useMessage().success('操作成功');
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};

const downloadFiles = async () => {
	downBlobFile(`admin/projectBasicInfo/projectBasicInfo/exportAll`, state.queryForm, `项目信息.zip`);

	// try {
	// 	const response = await axios.post("/api/admin/projectBasicInfo/exportAll", state.queryForm, {
	// 		headers: {
	// 			'Authorization': 'Bearer ' + Session.getToken()
	// 		},
	// 		responseType: "blob",
	// 	});
	//
	// 	const blob = new Blob([response.data], {
	// 		type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
	// 	});
	// 	const url = URL.createObjectURL(blob);
	// 	const a = document.createElement("a");
	// 	a.style.display = "none";
	// 	a.href = url;
	// 	const contentDisposition = response.headers["content-disposition"];
	// 	if (contentDisposition) {
	// 		const decodedHeader = decodeURIComponent(contentDisposition);
	// 		const match = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(
	// 				decodedHeader
	// 		);
	// 		if (match != null && match[1]) {
	// 			let fileName = match[1];
	// 			fileName = decodeURIComponent(fileName);
	// 			fileName = fileName.replace(/^utf-8''/, "");
	// 			a.download = fileName;
	// 		}
	// 	}
	// 	document.body.appendChild(a);
	// 	a.click();
	// 	URL.revokeObjectURL(url);
	// 	document.body.removeChild(a);
	// } catch (err) {
	// 	console.error(err);
	// }
};
const downloadFile = (item: any) => {
	other.downBlobFile(`/admin/sys-file/${item.bucketName}/${item.fileName}`, {}, item.original);
};
</script>
